package main

import (
	"bufio"
	"errors"
	"fmt"
	"image"
	"image/jpeg"
	"os"
	"strconv"
	"time"
)

func main() {
	file1, _ := os.Open(".\\img\\a1.jpg")
	//defer file1.Close()

	img1,conf,errRimg := image.Decode(bufio.NewReader(file1))
	if errRimg != nil {
		fmt.Println(errRimg)
	}
	fmt.Println(conf)  //jpeg

	var reject int = 25	//周边舍去reject像素
	//img1, _ := jpeg.Decode(file1)
	width, high := img1.Bounds().Dx(),img1.Bounds().Dy()
	validImg, err := cropimg(img1, reject, reject, width-2*reject, high-2*reject)

	nameImg := strconv.Itoa(int(time.Now().Unix()))
	imgw, err := os.Create(nameImg + "shuidaan.jpg")
	if err != nil {
		fmt.Println(err)
	}



	jpeg.Encode(imgw, validImg, &jpeg.Options{100})
	defer imgw.Close()
}

func cropimg(src image.Image, x, y, w, h int) (image.Image, error) {

	var subImg image.Image
	//subImg = src.SubImage(image.Rect(x, y, x+w, y+h))
	if rgbImg, ok := src.(*image.YCbCr); ok {
		subImg = rgbImg.SubImage(image.Rect(x, y, x+w, y+h)).(*image.YCbCr) //图片裁剪x0 y0 x1 y1
	} else if rgbImg, ok := src.(*image.RGBA); ok {
		subImg = rgbImg.SubImage(image.Rect(x, y, x+w, y+h)).(*image.RGBA) //图片裁剪x0 y0 x1 y1
	} else if rgbImg, ok := src.(*image.NRGBA); ok {
		subImg = rgbImg.SubImage(image.Rect(x, y, x+w, y+h)).(*image.NRGBA) //图片裁剪x0 y0 x1 y1
	} else {

		return subImg, errors.New("图片解码失败")
	}

	return subImg, nil
}